import axios from 'axios'
import { Toast } from 'vant'
import store from '../store'
import router from '@/router/index.js'
import { authorizationsPut } from '@/api/user.js'
const _aixos = axios.create({
  baseURL: process.env.VUE_APP_URL
})
_aixos.interceptors.request.use(
  config => {
    // 统一携带token 如果noToken 为false就携带
    if (!config.noToken) {
      config.headers.Authorization = `Bearer ${store.getters['user/getToken']}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
_aixos.interceptors.response.use(
  res => {
    return res.data
  },
  async error => {
    if (error.response.status === 401) {
      try {
        const refresh = await authorizationsPut()
        store.commit('user/setToken', refresh.data.token)
        return _aixos(error.config)
      } catch {
        if (error.response.data && error.response.data.message) {
          Toast.fail(error.response.data.message)
        }
        store.commit('user/setToken', '')
        router.push('/login?redirect=' + router.currentRoute.fullPath)
      }
    } else {
      // 统一错误处理
      // console.log([error])
      if (error.response.data && error.response.data.message) {
        Toast.fail(error.response.data.message)
      }
    }
    return Promise.reject(error)
  }
)
export default _aixos
